const axios = require('axios')
const key = '8fb45f16e078433d8490abc24be03baf' // 访问秘钥

var request = require('request-promise');
// axios.defaults.baseURL = "https://api.heweather.net/s6/weather";
let baseURL = 'https://widget-api.heweather.net/s6/plugin'

const getWeather = function (type = 'view', location) {
    let baseURL = "https://widget-api.heweather.net/s6/plugin";
    // if (type !== 'now' && type !== 'forecast' && type !== 'lifestyle') throw new Error('getWeather error: type类型错误');
    if (!location) throw new Error('getWeather error: location not defined');
    return request({
        url: `${baseURL}/${type}`,
        qs: {
            location,
            key
        },
        rejectUnauthorized: false,
        resolveWithFullResponse: true,
        json: true
    }).then(function (res) {
        // return res.data.HeWeather6[0];
        return res;
    }).catch((error) => {
        console.log(error, 'error');
    })
}

const initDay = async function ({ location }) {
    // let e = await getWeather('now', location);
    // this.subWeather = e.now.cond_txt;
    // this.curTemp = e.now.tmp;
    // this.webIcon = e.now.cond_code;
    return await getWeather('view', location)
}

const initDayDetail = async function ({ location }) {
    // let fore = await getWeather('forecast', location);
    // this.foreDays = fore.daily_forecast;
    // let life = await getWeather('lifestyle', location);
    // this.lifeStyle = life.lifestyle;
    // return {
    //     foreDays: await getWeather('view', location),
    //     lifeStyle: await getWeather('view', location)
    // }
    return await getWeather('view', location)
}

const searchCity = function ({ location }) {
    // find?key=8fb45f16e078433d8490abc24be03baf&group=cn&lang=zh&location=CN101010100
    baseURL = 'https://search.heweather.net'
    if (!location) throw new Error('searchCity error: location not defined');
    return request({
        url: `${baseURL}/find`,
        qs: {
            location,
            key
        },
        rejectUnauthorized: false,
        json: true
    }).then((res) => {
        // HeWeather6
        return (res && res.HeWeather6[0]) || {};
    }).catch((error) => {
        console.log(error, 'error');
    })
}

module.exports = {
    getWeather,
    initDay,
    initDayDetail,
    searchCity
}